﻿using KAs.Application.Contract.Svc;
using KAs.Common.Attr;
using SqlSugar;
using System.Reflection;

namespace KAs.Application;

public class AssembliesService : IAssembliesService
{
    private readonly List<Type> _entities = new();
    private readonly List<Type> _enums = new();
    private readonly List<string> _assemblyNames = new();

    public AssembliesService()
    {
        // 获取运行目录下所有程序集
        var path = AppDomain.CurrentDomain.BaseDirectory;
        string[] dllFiles = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly);
        // 循环获取符合条件的实体类或枚举
        foreach (string dllFile in dllFiles)
        {
            var assembly = Assembly.LoadFrom(dllFile);
            _assemblyNames.Add(assembly.GetName().Name);

            var types = assembly.GetTypes().Where(x => x.IsPublic && (x.IsEnum || x.IsClass));
            var enums = types.Where(x => x.IsEnum && x.GetCustomAttribute<ReadEnumAttribute>() != null);
            if (enums != null && enums.Any())
                _enums.AddRange(enums);
            var entities = types.Where(x => x.IsClass && x.GetCustomAttribute<SugarTable>() != null);
            if (entities != null && entities.Any())
                _entities.AddRange(entities);
        }
    }

    public List<Type> GetReadEnums()
    {
        return _enums;
    }

    public List<Type> GetEntities()
    {
        return _entities;
    }

    public List<string> GetAssemblyNames()
    {
        return _assemblyNames;
    }
}
